<template>
  <div
    v-page-show="{
      show: operate?.checkedProject,
      text: '请先选择项目'
    }"
  >
    <RePage>
      <div class="h-full">
        <splitpane :splitSet="settingLR">
          <template v-slot:paneL>
            <div class="pr-[16px] h-full">
              <treeList
                ref="treeListRef"
                :treeProops="treeProops"
                :treeEvents="treeEvents"
                :pageShow="false"
                :inputShow="false"
              />
            </div>
          </template>
          <template #paneR>
            <div class="pl-[16px]">
              <MyFormCreate
                :clear-event="getTableList"
                v-model="searchFrom"
                :rule="searchFormRules"
                :key="key"
              >
                <template #field-productId="scope">
                  <el-select
                    clearable
                    @clear="getTableList"
                    v-model="searchFrom.productId"
                    placeholder="请选择产品名称"
                    @change="v => scope.data.model.callback(v)"
                  >
                    <el-option
                      v-for="item in productTypes"
                      :key="item.productId"
                      :label="item.productName"
                      :value="item.productId"
                    ></el-option>
                  </el-select>
                </template>
                <template #field-systematicId="scope">
                  <el-cascader
                    :show-all-levels="false"
                    :props="propsasd"
                    v-model="systematicId"
                    style="width: 100%"
                    @change="systematicChange"
                    clearable
                    :options="systemlist"
                    @clear="getTableList"
                    placeholder="请选择所属系统"
                  />
                </template>
                <el-button type="primary" @click="DebounceGetTableList"
                  >搜索</el-button
                >
                <sj-button custom-type="sinfo" @click="DebounceResetting"
                  >重置</sj-button
                >
              </MyFormCreate>
              <div>
                <el-button
                  v-auth="'business.device.create'"
                  type="primary"
                  :icon="Plus"
                  @click="add(1)"
                  :disabled="!operate.checkedProject || isaddbuivice"
                  >添加设备</el-button
                >
                <el-button
                  v-auth="'business.device.create'"
                  type="primary"
                  :icon="Plus"
                  @click="add(2)"
                  :disabled="!operate.checkedProject || isaddbuivice"
                  >添加用传设备</el-button
                >
                <el-button
                  v-auth="'business.device.import'"
                  type="primary"
                  @click="importInfo"
                  plain
                  >导入</el-button
                >
                <el-button
                  v-auth="'business.device.import'"
                  type="primary"
                  @click="getdownload"
                  plain
                  >下载模板</el-button
                >
              </div>
              <pure-table
                class="mt-5"
                :data="tableData.data"
                :columns="initPureTableConfig(roleTableConfig)"
                showOverflowTooltip
                border
                @selection-change="selectionChange"
                :isShowPag="false"
              >
                <template #status="{ row }">
                  <el-tag :type="row.status === 1 ? 'success' : 'danger'">
                    {{ isNullOrEmpty(STRATEGYSTATUSTEXT[row.status]?.label) }}
                  </el-tag>
                </template>
                <template #commStatus="{ row }">
                  <el-tag :type="DEVICESTATUSTABLE[row.commStatus]?.type">
                    {{
                      isNullOrEmpty(DEVICESTATUSTABLE[row.commStatus]?.label)
                    }}
                  </el-tag>
                </template>
                <template #action="{ row }">
                  <el-space>
                    <sj-link
                      custom-type="sblue"
                      :underline="false"
                      @click="info(row)"
                      >查看</sj-link
                    >
                    <sj-link
                      v-auth="'business.device.update'"
                      custom-type="sblue"
                      :underline="false"
                      @click="edit(row)"
                      >编辑</sj-link
                    >
                    <sj-link
                      v-auth="'business.device.remove'"
                      custom-type="sred"
                      :underline="false"
                      @click="deletes(row)"
                      >删除</sj-link
                    >
                  </el-space>
                </template>
              </pure-table>
              <div class="mt-5">
                <el-pagination
                  v-model:current-page="searchFrom.page"
                  v-model:page-size="searchFrom.limit"
                  background
                  :layout="PAGE_LAYOUT"
                  :total="tableData.total"
                  @size-change="getTableList"
                  @current-change="getTableList"
                />
              </div>
            </div>
          </template>
        </splitpane>
      </div>
    </RePage>
    <!-- <deviceInfo v-model="centerDialogVisible"></deviceInfo> -->
  </div>
</template>
<script lang="ts" setup>
import { isNullOrEmpty, initPureTableConfig } from '@/utils/functions'
import splitpane, { ContextProps } from "@/components/ReSplitPane";
import { usePageVariablesStoreHook } from "@/store/modules/pageVariables";
const operate = usePageVariablesStoreHook().getOperate();
import { getfloorSelectList } from "@/api/operate/project-management/projectManagement/architectural-settings";
import {
  DEVICESTATUS,
  STRATEGYSTATUS,
  DEVICESTATUSTABLE,
  STRATEGYSTATUSTEXT
} from "@/constant/device-mangenment";
import { getProductType } from "@/api/operate/alarm-management/alarm-log/index";
import treeList from "@/components/treeList/treeList.vue";
import MyFormCreate from "@/components/MyFormCreate/index.vue";
import deviceInfo from "./device-info.vue";
import RePage from "@/components/RePage/index.vue";
import ReTable from "@/components/ReTable/index.vue";
import editForm from "./form.vue";
import infos from "./info.vue";
import importdecice from "./import-decice.vue";
import { reactive, ref, h } from "vue";
import { PAGE_LAYOUT } from "@/constant";
import { Plus, Delete } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  getList,
  getInfo,
  addInfo,
  editInfo,
  deleteInfo,
  systemdevice,
  importDevice,
  download
} from "@/api/operate/device-management/index";
import { facilitbuildings } from "@/api/operate/timed-tasks/index";
import { titles, defaultSearchForm, prompt, defaultInfoForm } from "./index";
import { addDialog } from "@/components/ReDialog";
import {
  cloneDeep,
  isAllEmpty,
  deviceDetection,
  debounce
} from "@pureadmin/utils";
import { message } from "@/utils/message";
import { customDebounce, customPromiseDebounce } from "@/utils/functions";
const route = useRoute()  // 获取路由参数
const childrenbuilding = ref();
const showBuildingId = ref(); //父级的建筑id
const drawingId = ref();
const treeListRef = ref();
const searchFrom = ref(defaultSearchForm());
const key = ref(0);
const systematicId = ref([]);
const showInfo = ref();
const formRef = ref();
const tableData = reactive({
  data: [],
  total: 0
});
const propsasd = {
  value: "systematicId",
  label: "systematicName",
  children: "child",
  checkStrictly: true
};
const centerDialogVisible = ref(false);
const productTypes = ref([]);
const systemlist = ref([]);
const searchFormRules = [
  {
    type: "input",
    field: "gatewaySN",
    title: titles.gatewaySN,
    props: {
      placeholder: prompt.gatewaySN,
      clearable: true
    }
  },
  {
    type: "input",
    field: "deviceId",
    title: titles.deviceId,
    props: {
      placeholder: prompt.deviceId,
      clearable: true
    }
  },
  {
    type: "fieldComponent",
    field: "productId",
    title: titles.productId,
    value: null,
    options: productTypes,
    props: {
      placeholder: prompt.productId,
      clearable: true
    }
  },
  {
    type: "input",
    field: "deviceSN",
    title: titles.deviceSN,
    value: null,
    props: {
      placeholder: prompt.deviceSN,
      clearable: true
    }
  },
  {
    type: "select",
    field: "commStatus",
    title: titles.commStatus,
    value: null,
    options: DEVICESTATUS,
    props: {
      placeholder: prompt.commStatus,
      clearable: true
    }
  },
  {
    type: 'select', field: 'isWillExpired', title: titles.isWillExpired, value: null,
    options: [
      { label: '即将到期', value: 1 },
    ],
    props: {
      placeholder: prompt.isWillExpired, clearable: true
    }
  },
  {
    type: "fieldComponent",
    field: "systematicId",
    title: titles.systematicId,
    value: null,
    props: {
      placeholder: prompt.systematicId,
      clearable: true
    }
  },
  {
    type: "select",
    field: "status",
    title: titles.status,
    value: null,
    options: STRATEGYSTATUS,
    props: {
      placeholder: prompt.status,
      clearable: true
    }
  },
  { type: "number", field: "page", title: "page", hidden: true },
  { type: "number", field: "limit", title: "limit", hidden: true }
];
const selectionData = ref([]);
const roleTableConfig = [
  { type: "selection", align: "left", fixed: "left" },
  { prop: "id", label: titles.id, width: 100, fixed: "left" },
  { prop: "productName", label: titles.productName, minWidth: 160 },
  { prop: "deviceSN", label: titles.deviceSN, minWidth: 160 },
  { slot: "commStatus", label: titles.commStatus, minWidth: 160 },
  { prop: "systematicName", label: titles.systematicId, minWidth: 160 },
  // { prop: "systemName", label: titles.systemName },
  { slot: "status", label: titles.status, minWidth: 90 },
  { slot: "action", label: titles.action, width: 150, fixed: "right" }
];
// 获取列表数据
const getTableList = () => {
  getList(searchFrom.value).then(res => {
    if (res.code === 200) {
      tableData.data = res.result.data;
      tableData.total = res.result.total;
    }
  });
};
const settingLR: ContextProps = reactive({
  minPercent: 10,
  maxPercent: 10,
  defaultPercent: 15,
  split: "vertical"
});
// 重置搜索栏
const resetting = () => {
  //点击重置按键
  Object.assign(searchFrom.value, defaultSearchForm());
  systematicId.value = null;
  key.value++;
  getTableList();
};
// 详情
const info = row => {
  // centerDialogVisible.value = true;
  addDialog({
    title: `设备信息`,
    width: "1190px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      id: row.id
    },
    hideFooter: true,
    contentRenderer: () => h(deviceInfo, { ref: formRef }),
    openAutoFocus({ options, index }) {
      options.props = {
        isLoading: true,
        newFormInline: null,
        id: row.id
      };
      getInfo({ id: row.id })
        .then(res => {
          if (res.code == 200) {
            showInfo.value = res.result;
            options.props.newFormInline = res.result;
          }
        })
        .finally(() => {
          options.props.isLoading = false;
        });
    }
  });
};
// 新增
const add = e => {
  showInfo.value = {};
  openDialog('新增', {}, e);
};
// 编辑
const edit = row => {
  showInfo.value = {};
  openDialog("编辑", row);
};
// 删除
const deletes = (row?) => {
  ElMessageBox.confirm(`确认删除${row ? "当前" : "选中的"}数据?`, "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning"
  }).then(() => {
    deleteInfo({
      ids: row ? [row.id] : selectionData.value.map(item => item.id)
    }).then(res => {
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: "删除成功"
        });
        getTableList();
      }
    });
  });
};
//数形事件
const isLoading = ref(true);
const treeRef = ref();
const isaddbuivice = ref(true);
const checkedUnitId = ref(null);
const handleNodeClick = data => {
  if (data.buildingName !== "全部") {
    isaddbuivice.value = false;
  }
  if (data.buildingName !== "项目平面") {
    isaddbuivice.value = false;
  }
  if (data.drawingId == undefined && data.buildingName !== "项目平面") {
    isaddbuivice.value = true;
  }
  childrenbuilding.value = data.buildingId;
  drawingId.value = data.drawingId;
  showBuildingId.value = data.showBuildingId;
  switch (true) {
    case data.buildingId == "0":
      searchFrom.value.projectId = "";
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = "";
      isaddbuivice.value = true;
      getTableList();
      return;
    case data.buildingId === "01":
      searchFrom.value.projectId = operate.checkedProject;
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = "";
      getTableList();
      return;
    case data.drawingId !== undefined:
      searchFrom.value.prodcutId = "";
      searchFrom.value.buildingId = "";
      searchFrom.value.drawingId = data.drawingId;
      getTableList();
      return;
    case data.buildingId !== 0:
      searchFrom.value.prodcutId = "";
      searchFrom.value.buildingId = data.buildingId;
      searchFrom.value.drawingId = "";
      getTableList();
      return;
  }
};
const props = {
  label: "buildingName",
  value: "buildingId",
  children: "children"
  // isLeaf: "isLeaf"
};

const projectList = ref([]);
onMounted(() => {
  if (route.query.commStatus) {
    searchFrom.value.commStatus = Number(route.query.commStatus)
    key.value++
  }
  if (route.query.isWillExpired) {
    searchFrom.value.isWillExpired = Number(route.query.isWillExpired)
    key.value++
  }
  if (route.query.systematicId) {
    searchFrom.value.systematicId = Number(route.query.systematicId)
    key.value++
  }
  if (operate?.checkedProject) {
    loadProjectList().then(() => {
      treeListRef.value
        .getTreeRef()
        .setCurrentKey(projectList.value[0].buildingId);
      searchFrom.value.buildingId = projectList.value[0].buildingId;
      getTableList();
    });
    getProductType().then(res => {
      if (res.code === 200) {
        productTypes.value = res.result;
        key.value++;
      }
    });
    systemdevice().then(res => {
      if (res.code === 200) {
        systemlist.value = res.result;
        if (searchFrom.value.systematicId) {
          systematicId.value = getSystematicIdArray() ?? []
        }
        key.value++;
      }
    });
  }
});
const getSystematicIdArray = (list = systemlist.value) => {
  for (let index = 0; index < list.length; index++) {
    const item = list[index];
    if (item.child) {
      if (item.systematicId == searchFrom.value.systematicId) {
        return [item.systematicId]
      } else {
        let res = getSystematicIdArray(item.child)
        if (res?.length > 0) {
          res.unshift(item.systematicId)
          return res
        }
      }
    } else {
      if (item.systematicId == searchFrom.value.systematicId) {
        return [item.systematicId]
      }
    }
  }
}

// 下载模板
const getdownload = () => {
  download().then(res => {
    console.log("下载模板", res);

    const url = window.URL.createObjectURL(res)
    const link = document.createElement('a')
    link.style.display = 'none'
    link.href = url
    link.setAttribute('download', '导入模板.xlsx')
    document.body.appendChild(link)
    link.click()
    link.remove()
  })
}

const importInfo = () => {
  addDialog({
    title: `文件导入`,
    width: "800px",
    draggable: true,
    props: {
      importForm: {
        file: null
      }
    },
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    contentRenderer: () => h(importdecice, { ref: formRef }),
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          let formData = new FormData();
          for (let key in options.props.importForm) {
            formData.append(key, options.props.importForm[key]);
          }
          console.log("formData", options.props.importForm);

          DebounceImportDevice(formData).then(res => {
            if (res.code == 200) {
              chores();
            }
            options.props.isLoading = false;
          }).catch((err) => {
            if (err !== '请求中') {
              options.props.isLoading = false;
            }
          })
        }
      })
    }
  });
}
const defultProjectList = () => [];
const treeEvents = {
  nodeClick: handleNodeClick
};
const checkedProject = ref(0);
//获取数据
const loadProjectList = () => {
  return new Promise((resolve, reject) => {
    isLoading.value = true;
    facilitbuildings()
      .then(res => {
        // let aaa = defultProjectList();
        let arrs = [
          {
            buildingId: "0",
            buildingName: "全部",
            children: []
          },
          {
            buildingId: "01",
            prodcutId: res.result.prodcutId,
            buildingName: "项目平面",
            children: []
          }
        ];
        res.result.buildingInfo.unshift(...arrs);
        res.result.buildingInfo.forEach(item => {
          if (item.children.length > 0) {
            item.children.forEach(item1 => {
              item1.showBuildingId = item.buildingId;
              item1.buildingId = item1.drawingId + "-1" + item.buildingId;
              item1.buildingName = item1.drawingName;
            });
          }
        });
        projectList.value = res.result.buildingInfo;
      })
      .finally(() => {
        isLoading.value = false;
        resolve("");
      });
    checkedProject.value = 0;
  });
};
// 开启弹窗
const openDialog = (title = "新增", row?: any, type = 1) => {
  let sidebar = ref(defaultInfoForm());
  sidebar.value.buildingId = showBuildingId.value;
  sidebar.value.drawingId = drawingId.value;
  sidebar.value.childrenbuilding = childrenbuilding.value;
  if (showBuildingId.value == undefined && drawingId.value == undefined) {
    //选择全部和平面时所在位置必须是室外
    sidebar.value.position = 2;
  } else {
    sidebar.value.position = 1;
  }
  addDialog({
    title: `${title}`,
    width: "800px",
    draggable: true,
    fullscreen: deviceDetection(),
    fullscreenIcon: true,
    closeOnClickModal: false,
    props: {
      isLoading: false,
      isEdit: !!row,
      originMarker: {},
      type: type,
      formInline: defaultInfoForm()
    },
    contentRenderer: () => h(editForm, { ref: formRef }),
    openAutoFocus({ options, index }) {
      if (row.id) {
        options.props = {
          isLoading: true,
          isEdit: true,
          type: row?.deviceKind ,
          originMarker: {},
          formInline: defaultInfoForm()
        };
        getInfo({ id: row.id })
          .then(res => {
            if (res.code == 200) {
              showInfo.value = res.result;
              options.props.formInline = res.result;
              options.props.originMarker = res.result.drawingPoint
              options.props.type = res.result.deviceKind 
            }
          })
          .finally(() => {
            options.props.isLoading = false;
          });
      } else {
        options.props = {
          isLoading: false,
          isEdit: false,
          type: type,
          formInline: sidebar.value
        };
        options.props.formInline.buildingId = showBuildingId.value;
        options.props.formInline.drawingId = drawingId.value;
      }
    },
    beforeSure: (done, { options }) => {
      const FormRef = formRef.value.getRef();
      let formData = options.props.formInline;
      function chores() {
        message(`操作成功`, {
          type: "success"
        });
        done(); // 关闭弹框
        getTableList(); // 刷新表格数据
      }
      FormRef.validate(valid => {
        if (valid && !options.props?.isLoading) {
          // console.log("formData", formData);
          // 表单规则校验通过
          options.props.isLoading = true;
          if (title === "新增") {
            formData.deviceKind=options.props.type
            DebounceAddInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          } else {
            DebounceEditInfo(formData)
              .then(res => {
                if (res.code == 200) {
                  chores();
                }
                options.props.isLoading = false;
              })
              .catch(err => {
                if (err !== "请求中") {
                  options.props.isLoading = false;
                }
              });
          }
        }
      });
    }
  });
};
const systematicChange = e => {
  console.log(e, 'systematicChange');

  if (e && e.length > 0) {
    searchFrom.value.systematicId = e[e.length - 1];
  } else {
    searchFrom.value.systematicId = null;
    getTableList()
  }
};
// const changecascader=()=>{
//   console.log("清空")
// }
const filterMethod = (query, node) => {
  return node.buildingName.includes(query);
};
const treeProops = ref({
  props: props,
  data: projectList,
  "item-size": 42,
  "filter-method": filterMethod,
  nodeKey: "buildingId",
  "highlight-current": true
});
const selectionChange = data => {
  selectionData.value = data;
};
// 获取列表
const DebounceGetTableList = debounce(getTableList, 1000, true);
// 重置
const DebounceResetting = debounce(resetting, 1000, true);
// 添加请求
const DebounceAddInfo = customPromiseDebounce(addInfo, 1000, true);
// 编辑请求
const DebounceEditInfo = customPromiseDebounce(editInfo, 1000, true);
// 导入
const DebounceImportDevice = customPromiseDebounce(importDevice, 1000, true);
</script>
<style lang="scss" scoped></style>
